package cn.cd.anStudio;

import java.util.ArrayList;
import java.util.List;

import cn.cd.anStudio.CommonUtil.AnstudioSynDialog;
import cn.cd.anStudio.io.MyBusNetUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class MyBusLocationActivity extends Activity
                                   implements OnFocusChangeListener {
	
	private static final String TAG = "MyBusLocationActivity";
	
	private EditText busNum          = null;
	private Spinner  srcList         = null;
	private Spinner  desList         = null;
	private Spinner  alertList       = null;
	private Button   stopsInDetail   = null;
	private Button   locationConfirm = null;
	private Button   locationExit    = null;
	private AlertDialog stopsDetailDialog = null;
	private int      busDirection    = -1;
	
	private String busSrc = null;
	private String alertKey = null;
	private int queryType = -1;
	
	private MyBusInfo curBusInfo = new MyBusInfo();
	public Object myBusLock = new Object();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);

    	busSrc    = null;
    	alertKey  = null;
    	queryType = 0;
        
        setContentView(R.layout.location);

        busNum = (EditText) findViewById(R.id.location_bus_input);
        busNum.setOnFocusChangeListener(this);

        srcList = (Spinner) findViewById(R.id.location_src_candidate);
        desList = (Spinner) findViewById(R.id.location_des_candidate);
        alertList = (Spinner) findViewById(R.id.location_alert_candidate);

        stopsInDetail   = (Button) findViewById(R.id.location_des_detail);
        locationConfirm = (Button) findViewById(R.id.location_confirm);
        locationExit    = (Button) findViewById(R.id.location_exit);

        stopsInDetail.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				showStopsInDetail();
			}
        });
        
        alertList.setOnItemSelectedListener(new OnItemSelectedListener(){

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				alertKey = arg0.getItemAtPosition(arg2).toString();
				Log.v(TAG, "alertKey:       " + alertKey);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
        	
        });
        
        srcList.setOnItemSelectedListener(new OnItemSelectedListener(){

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				busSrc = arg0.getItemAtPosition(arg2).toString();
				Log.v(TAG, "busSrc:       " + busSrc);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
        	
        });
        
        locationConfirm.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				Log.v(TAG, "Start query service");

				int queryContinue = -1;

				// Check whether this moment is valid bus schedule time
		        if (!curBusInfo.isBusValidThisTime()) {
		        	AnstudioSynDialog queryExpireDialog =
		        			new AnstudioSynDialog((Activity)arg0.getContext()
		        					, arg0.getContext().getResources().getString(R.string.location_query_time_invalid_error)
				        	        , arg0.getContext().getResources().getString(R.string.common_continue)
				        	        , arg0.getContext().getResources().getString(R.string.common_cancle));

				        	queryExpireDialog.showDialog();
				        	queryContinue = queryExpireDialog.getDialogResult();
				        	
				        	if (DialogInterface.BUTTON2 == queryContinue) {
				        		Log.v(TAG, "User cancelled this service");
				        		return;
				        	}
				}
		        
		        if (null == alertKey)
		        	alertKey = alertList.getItemAtPosition(alertList.getFirstVisiblePosition()).toString();
		        
		        if (null == busSrc)
		        	busSrc = srcList.getItemAtPosition(alertList.getFirstVisiblePosition()).toString();
		        
				if ((null == alertKey)
						||(null == busSrc)
						||(queryType < 0)) {
		        	AnstudioSynDialog queryErrorDialog =
		        			new AnstudioSynDialog((Activity)arg0.getContext()
		        					, arg0.getContext().getResources().getString(R.string.location_query_service_start_error)
				        	        , arg0.getContext().getResources().getString(R.string.common_ok)
				        	        , null);

		        	        queryErrorDialog.showDialog();
				        	return;
				}
				
				Intent iIntent = new Intent();
				iIntent.setAction("com.cn.cd.anstudio.service.MYBUSLOCATION");
				iIntent.putExtra("keyWord", alertKey);
				iIntent.putExtra("busNum", busNum.getText().toString());
				iIntent.putExtra("busStop", busSrc);
				iIntent.putExtra("queryType", queryType);
				startService(iIntent);
				finish();
			}
        });
        
        locationExit.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				Intent iIntent = new Intent();
				iIntent.setAction("com.cn.cd.anstudio.service.MYBUSLOCATION");
				stopService(iIntent);
				finish();
			}
        });
    }
    
    private void setAdapterForSpinner(Spinner sp, List<String> spList) {
    	
    	ArrayAdapter<String> spAdapter =
				new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spList);
    	
    	sp.setAdapter(spAdapter);
    }
    
    private void showStopsInDetail() {
    	
    	String busStops = getResources().getString(R.string.location_des_detail);
    	
    	android.content.DialogInterface.OnClickListener listDialogListener = 
    			new android.content.DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				//dissStopsInDetail();
				dialog.dismiss();
			}
    	};

    	if (0 == busDirection) {
    		for(String stop : curBusInfo.getBusstopList1()) {
    			busStops = busStops + "\n" + stop;
    		}
    	} else {
    		for(String stop : curBusInfo.getBusstopList2()) {
    			busStops = busStops + "\n" + stop;
    		}
    	}
    	
    	busStops = busStops + "\n";
    	
    	stopsDetailDialog = new AlertDialog.Builder(this).create();
		stopsDetailDialog.setMessage(busStops);
		stopsDetailDialog.setButton(
				  getResources().getString(R.string.common_ok)
				, (android.content.DialogInterface.OnClickListener)listDialogListener);

		stopsDetailDialog.show();
    }

	public void onFocusChange(View arg0, boolean arg1) {
		if (arg0.equals(busNum)) {
			if (!arg1) {
				
				if (MyBusCommonBase.DEBUG)
					Log.v(TAG, "Bus Num Editor lose focus");
				
				AlertDialog getBusErrorDialog = null;

				android.content.DialogInterface.OnClickListener getBusErrorListener =
						new android.content.DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
					
				};

				//Set data for spinner which indicates the direction
				//1. Get bus information by net
				ProgressDialog myBusWaitBusInfoDialog =
						new ProgressDialog(arg0.getContext());
				myBusWaitBusInfoDialog.setMessage("waiting");
				myBusWaitBusInfoDialog.setIndeterminate(true);
				myBusWaitBusInfoDialog.show();
				
				// Folk a new thread to gain web data
				new Thread(new Runnable() {

					public void run() {
						MyBusNetUtil busNetUtil = new MyBusNetUtil();
						curBusInfo = busNetUtil.getBusInfoByNet(busNum.getText().toString());
						synchronized(myBusLock) {
							myBusLock.notify();
						}
					}
				}).start();
				
				synchronized (myBusLock) {
					try {
						myBusLock.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				myBusWaitBusInfoDialog.dismiss();

				//2. Generate view adapter for spinner
				List<String> curBusDeses = new ArrayList<String>();
				curBusDeses.add(curBusInfo.getBusStart1()
						+ "->"
						+ curBusInfo.getBusTerm1());
				if (MyBusInfo.BUS_BI_DIRECTION == curBusInfo.getRouteType()) {
					curBusDeses.add(curBusInfo.getBusStart2()
							+ "->"
							+ curBusInfo.getBusTerm2());
				}
				
				if ((curBusInfo.getBusStart1() == null)
						||(curBusInfo.getBusStart2() == null)
						||(curBusInfo.getBusTerm1() == null)
						||(curBusInfo.getBusTerm2() == null)) {
					getBusErrorDialog = new AlertDialog.Builder(this).create();
					getBusErrorDialog.setMessage(this.getResources().getString(R.string.location_get_bus_info_error));
					getBusErrorDialog.setButton(this.getResources().getString(R.string.common_ok), getBusErrorListener);
					getBusErrorDialog.show();
					
					return;
				}
				
				//3. Set adapter to spinner
				setAdapterForSpinner(desList, curBusDeses);
				
				//Set data for spinner which indicates the current valid bus stops
				desList.setOnItemSelectedListener(new OnItemSelectedListener() {

					//FIXME : A bit tricky here : listener within listener
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						
						List<String> validBusStops = new ArrayList<String>();
						if (0 == arg2) {
							//Branch through routine up
							for (String stop : curBusInfo.getBusstopList1()) {
								validBusStops.add(stop);
								queryType = 0;
							}
						} else {
							//Branch through routine down
							for (String stop : curBusInfo.getBusstopList2()) {
								validBusStops.add(stop);
								queryType = 1;
							}
						}
						
						busDirection = arg2;
						
						setAdapterForSpinner(srcList, validBusStops);
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						
					}
				});

			}

		}
		
	}
}
